﻿using System.Linq;
using UnityEditor;
using UnityEngine;

namespace Gp.Scripts.Editor
{
    [TopToolbarDrawer(order: 10)]
    public class SceneCameraDrawer : ITopToolbarDrawer
    {
        private const string SAVE_KEY = "Show Scene Camera";
        public SceneCameraDrawer()
        {
            EditorApplication.playModeStateChanged += OnPlayModeChange;
            SceneView.duringSceneGui += CreateCameraFunc;
            return;

            void CreateCameraFunc(SceneView _)
            {
                if (!EditorPrefs.GetBool(SAVE_KEY, false)) return;
                BuildSceneCamera();
                SceneView.duringSceneGui -= CreateCameraFunc;
            }
        }

        private void OnPlayModeChange(PlayModeStateChange state)
        {
            if (SceneCameraHook.Instance != null)
            {
                EditorCommonUtils.SmartDestroy(SceneCameraHook.Instance.gameObject);
            }


            // 重新进入playMode时，管理场景相机载入
            if (state == PlayModeStateChange.EnteredEditMode)
            {
                SceneCameraHook.ShowSceneCamera
                    = EditorPrefs.GetBool("Show Scene Camera", SceneCameraHook.ShowSceneCamera);
                if (SceneCameraHook.ShowSceneCamera)
                    BuildSceneCamera();
            }
        }


        private void BuildSceneCamera()
        {
            var camera = Resources.Load<GameObject>("EditorOnly/SceneCamera");
            if (camera)
            {
                var cam = PrefabUtility.InstantiatePrefab(camera, this.GetSceneCameraTransform()) as GameObject;
                cam.tag = "EditorOnly";
                cam.name = "__SceneCamera";
                cam.AddComponent<SceneCameraHook>();
                cam.hideFlags = HideFlags.HideAndDontSave;
            }
            else
            {
                Debug.LogError("Editor-[关卡编辑工具]: SceneCamera prefab丢失");
            }

            Debug.Log("Editor-[关卡编辑工具]: Build SceneCamera successfully");
            SceneCameraHook.ShowSceneCamera = true;
            EditorPrefs.SetBool("Show Scene Camera", true);
        }


        public void OnToolbarGUI()
        {
            GUILayout.FlexibleSpace();


            if (GUILayout.Button("卸载摄像机"))
            {
                SceneCameraHook.ShowSceneCamera = false;
                EditorPrefs.SetBool(SAVE_KEY, false);
                var cam = SceneView.GetAllSceneCameras().First().transform.Find("__SceneCamera");
                if (cam && cam.CompareTag("EditorOnly") && cam.GetComponent<Camera>())
                {
                    EditorCommonUtils.SmartDestroy(cam.gameObject);
                }

                SceneView.RepaintAll();
            }

            if (GUILayout.Button(new GUIContent("载入摄像机")) && SceneCameraHook.Instance == null)
            {
                BuildSceneCamera();
            }
        }
    }
}